const { query, run } = require('../database/db');

// 获取用户购物车
async function getCart(userId) {
    return await query(`
        SELECT c.*, p.name, p.price, p.image_url, p.stock 
        FROM cart c 
        JOIN products p ON c.product_id = p.id 
        WHERE c.user_id = ?
    `, [userId]);
}

// 添加商品到购物车
async function addToCart(userId, productId, quantity = 1) {
    // 检查商品是否已在购物车中
    const existing = await query(
        'SELECT * FROM cart WHERE user_id = ? AND product_id = ?',
        [userId, productId]
    );

    if (existing.length > 0) {
        // 更新数量
        await run(
            'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?',
            [quantity, userId, productId]
        );
    } else {
        // 添加新商品
        await run(
            'INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)',
            [userId, productId, quantity]
        );
    }
}

// 更新购物车商品数量
async function updateCartItem(userId, productId, quantity) {
    await run(
        'UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ?',
        [quantity, userId, productId]
    );
}

// 从购物车移除商品
async function removeFromCart(userId, productId) {
    await run(
        'DELETE FROM cart WHERE user_id = ? AND product_id = ?',
        [userId, productId]
    );
}

// 清空购物车
async function clearCart(userId) {
    await run('DELETE FROM cart WHERE user_id = ?', [userId]);
}

// 计算购物车总价
async function calculateTotal(userId) {
    const items = await query(`
        SELECT c.quantity, p.price 
        FROM cart c 
        JOIN products p ON c.product_id = p.id 
        WHERE c.user_id = ?
    `, [userId]);

    return items.reduce((total, item) => total + (item.quantity * item.price), 0);
}

module.exports = {
    getCart,
    addToCart,
    updateCartItem,
    removeFromCart,
    clearCart,
    calculateTotal
}; 